package com.infoland.afanmall.model.pinTuan.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.ToxicBakery.viewpager.transforms.DefaultTransformer;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.StatusBarKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.banner.HolderCreator;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.base.view.popWindow.CustomPopWindow;
import com.infoland.afanmall.model.pinTuan.adapter.PinTAdapter;
import com.infoland.afanmall.model.pinTuan.entity.PinTEntity;
import com.infoland.afanmall.model.zhongChou.entity.ZhongChouBanner;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 王永吉
 * @date 2018/7/12 8:20
 * 拼团界面
 */
public class PinTuanActivity extends AppCompatActivity {
    //头部标题布局
    @BindView(R.id.title_layout)
    LinearLayout titleLayout;
    //轮播
    @BindView(R.id.zhong_chou_banner)
    ConvenientBanner<String> pinTuanBanner;
    //头部标题
    @BindView(R.id.info_text)
    TextView infoText;
    //最新排序按钮
    @BindView(R.id.ptuan_rad_zui_xin)
    RadioButton ptuanRadZuiXin;
    //成团数排序按钮
    @BindView(R.id.ptuan_rad_cheng_tuan)
    RadioButton ptuanRadChengTuan;
    //已拼数量排序按钮
    @BindView(R.id.ptuan_rad_yi_pin)
    RadioButton ptuanRadYiPin;
    //top页tab
    @BindView(R.id.you_xuan_tab)
    LinearLayout youXuanTab;
    //商品列表
    @BindView(R.id.zhong_chou_recycle)
    RecyclerView zhongChouRecycle;
    //加载布局
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    //适配器
    PinTAdapter pinTAdapter;
    //活动id
    int activityId = 1;
    //点点点按钮
    @BindView(R.id.info_dian_dian_dian)
    ImageView infoDianDianDian;

    public int getContentView() {
        return R.layout.pin_tuan_activity;
    }

    //初始方法
    private void initData() {
        getBanner();
        //初始加载数据
        loadData();
        zhongChouRecycle.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        selectCheck(0);
    }

    //获取拼团Banner
    private void getBanner() {
        JSONObject para = new JSONObject();
        para.put("placeType", CONST.PinTuan.BANNER_TYPE);
        new OkHttpKit().send(
                response200 -> {
                    List<ZhongChouBanner> zhongChouBanners = JSONArray.parseArray(response200, ZhongChouBanner.class);
                    setBanner(zhongChouBanners);
                },
                success401 -> {
                    LogKit.E("success401 ---->   ", "  " + success401);
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                }
        ).post(CONST.BANNER_YX, para, this);

    }

    //设置拼团Banner
    private void setBanner(List<ZhongChouBanner> zhongChouBanners) {
        ArrayList<String> images = new ArrayList<>();
        for (ZhongChouBanner zanner : zhongChouBanners) {
            images.add(zanner.getF_url());
        }
        pinTuanBanner.setOnItemClickListener((position) -> {
        });
        pinTuanBanner.setPages(new HolderCreator(), images)
//                .setPageIndicator(new int[]{R.drawable.dot_normal, R.drawable.dot_focus})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setPageTransformer(new DefaultTransformer())
                .startTurning(3000)
                .setCanLoop(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentView());
        ButterKnife.bind(this);
        infoText.setText("阿凡拼团");
        StatusBarKit.immersiveBlackTitleText(this);//沉浸黑字
        StatusBarKit.setPaddingSmart(this, titleLayout);
        if (getIntent().getExtras() != null) {
            activityId = getIntent().getExtras().getInt("activityId");
        }
        initData();
    }

    //点击已拼数
    private void clickYiPin() {
        CacheKit.PinTuan.YP_SHU_LIANG = !CacheKit.PinTuan.YP_SHU_LIANG;
        CacheKit.PinTuan.ZUI_XIN = false;
        CacheKit.PinTuan.C_TUAN_SHU = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.YP_SHU_LIANG) {
            orderBy.put("buy_count", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiageshang);
        } else {
            orderBy.put("buy_count", "desc");
            ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiagexia);
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    //点击成团数
    private void clickChengTuan() {

        CacheKit.PinTuan.C_TUAN_SHU = !CacheKit.PinTuan.C_TUAN_SHU;
        CacheKit.PinTuan.ZUI_XIN = false;
        CacheKit.PinTuan.YP_SHU_LIANG = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.C_TUAN_SHU) {
            orderBy.put("group_count", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadChengTuan, R.mipmap.jiageshang);
        } else {
            orderBy.put("group_count", "desc");
            ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiagexia);
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    // 点击最新
    private void clickZuiXin() {
        CacheKit.PinTuan.ZUI_XIN = !CacheKit.PinTuan.ZUI_XIN;
        CacheKit.PinTuan.C_TUAN_SHU = true;
        CacheKit.PinTuan.YP_SHU_LIANG = true;
        JSONObject orderBy = new JSONObject();
        if (CacheKit.PinTuan.ZUI_XIN) {
            orderBy.put("create_time", "asc");
            ToolsKit.setRadioDrawableRight(ptuanRadZuiXin, R.mipmap.jiageshang);
        } else {
            orderBy.put("create_time", "desc");
            ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiagexia);
        }
        CacheKit.PinTuan.NOW_ORDER_BY = orderBy;
        CacheKit.PinTuan.NOW_PAGE_NUMBER = 1;
        getFirstPtData(CacheKit.PinTuan.NOW_PAGE_NUMBER, CacheKit.PinTuan.NOW_PAGE_SIZE, CacheKit.PinTuan.NOW_ORDER_BY);
    }

    //    查询第一页数据
    private void getFirstPtData(int nowPageNumber, int nowPageSize, JSONObject nowOrderBy) {
        CacheKit.YouXuan.NOW_PAGE_NUMBER = 1;
        CacheKit.YouXuan.NOW_PAGE_LAST = false;
        JSONObject para = new JSONObject();
        para.put("pageNumber", nowPageNumber);
        para.put("pageSize", nowPageSize);
        para.put("orderBy", nowOrderBy);
        para.put("activityId", activityId);
        LogKit.E("aaaa ---->   ", "  " + para);
        startLoading();
        new Handler().postDelayed(() -> {
            stopLoading();
            initAdapter();
        }, 1000);

    }

    private void initAdapter() {
        ArrayList<PinTEntity> arrayList = new ArrayList<>();
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        arrayList.add(new PinTEntity());
        pinTAdapter = new PinTAdapter(0, arrayList);
        zhongChouRecycle.setAdapter(pinTAdapter);
        pinTAdapter.setOnItemClickListener((adapter, view, position) -> {
            ToolsKit.go(PinTuanInfoActivity.class);
        });
    }

    //下拉加载数据
    private void loadData() {
        JSONObject para = new JSONObject();
        LogKit.E("aaaa ---->   ", "  " + CacheKit.YouXuan.NOW_PAGE_LAST);
        if (CacheKit.YouXuan.NOW_PAGE_LAST) {
            ToastUtils.showShort("已经最后一页");
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.finishLoadMore();
        } else {
            para.put("pageNumber", (CacheKit.PinTuan.NOW_PAGE_NUMBER += 1));
            para.put("pageSize", CacheKit.PinTuan.NOW_PAGE_SIZE);
            para.put("orderBy", CacheKit.PinTuan.NOW_ORDER_BY);
            para.put("activityId", activityId);
//            aviPt.setVisibility(View.VISIBLE);
            refreshLayout.setEnableLoadMore(false);
            new OkHttpKit().send(
                    response200 -> {
                        stopLoading();
                        LogKit.E("拼团商品 ---->   ", "  " + response200);
                    },
                    success401 -> {
                        LogKit.E("success401 ---->   ", "  " + success401);
                    },
                    error -> {
                        LogKit.E("error ---->   ", "  " + error);
                    }
            ).post(CONST.PinTuan.URL_GET_LIST, para, this);
        }
    }

    //清空所有样式
    public void clearClick() {
        ptuanRadZuiXin.setChecked(false);
        ptuanRadChengTuan.setChecked(false);
        ptuanRadYiPin.setChecked(false);
        ToolsKit.setRadioDrawableRight(ptuanRadZuiXin, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(ptuanRadChengTuan, R.mipmap.jiagemoren);
        ToolsKit.setRadioDrawableRight(ptuanRadYiPin, R.mipmap.jiagemoren);

    }

    //选中按钮
    public void selectCheck(int postion) {
        stopLoading();
        clearClick();
        switch (postion) {
            case 0:
                ptuanRadZuiXin.setChecked(true);
                clickZuiXin();
                break;
            case 1:
                ptuanRadChengTuan.setChecked(true);
                clickChengTuan();
                break;
            case 2:
                ptuanRadYiPin.setChecked(true);
                clickYiPin();
                break;
            default:
                break;
        }

    }

    private void startLoading() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setVisibility(View.GONE);
    }

    private void stopLoading() {
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
        refreshLayout.setEnableLoadMore(true);
//        aviPt.setVisibility(View.GONE);
        refreshLayout.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.info_back, R.id.info_close_all, R.id.info_dian_dian_dian, R.id.ptuan_rad_zui_xin, R.id.ptuan_rad_cheng_tuan, R.id.ptuan_rad_yi_pin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //返回
            case R.id.info_back:
                finish();
                break;
            //关闭
            case R.id.info_close_all:
                finish();
                break;
            //点点点按钮
            case R.id.info_dian_dian_dian:
                openTopRightMenu();
                break;
            //最新排序按钮
            case R.id.ptuan_rad_zui_xin:
                ToolsKit.setSleep1000(ptuanRadZuiXin);
                selectCheck(0);
                break;
            //成团排序按钮
            case R.id.ptuan_rad_cheng_tuan:
                ToolsKit.setSleep1000(ptuanRadChengTuan);
                selectCheck(1);
                break;
            //已拼数量排序按钮
            case R.id.ptuan_rad_yi_pin:
                ToolsKit.setSleep1000(ptuanRadYiPin);
                selectCheck(2);
                break;
        }
    }

    CustomPopWindow mCustomPopWindow;

    //     todo 打开右上角菜单
    private void openTopRightMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.open_top_right_menu, null);
        System.out.println(infoDianDianDian.getWidth());
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .create()
                .showAsDropDown(infoDianDianDian, -420, 0);
        System.out.println(mCustomPopWindow.getWidth());
    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = v -> {
            if (mCustomPopWindow != null) {
                mCustomPopWindow.dissmiss();
            }
            String showContent = "";
        };
    }

    @Override
    public void onDestroy() {
        ToolsKit.deleteOKHttp(this);
        super.onDestroy();
    }
}
